
var express = require('express');
var router = express.Router();
var { userModel,orderModel } = require('../model/thy_model')
const jwt = require('jsonwebtoken')
router.get('/aaaa',(req,res)=>{
    // console.log(req.headers);
    res.send({code:200})
})
/* 发送验证码 */
router.post('/sendCode', async function (req, res, next) {
    const info = req.body
    let phoneCode = Math.random() * 9000 // 生成验证码
    phoneCode = 1000 + parseInt(phoneCode) + ""
    console.log("我是生成的验证码：", phoneCode);
    // Depends on tencentcloud-sdk-nodejs version 4.0.3 or higher
    const tencentcloud = require("tencentcloud-sdk-nodejs-sms");

    const SmsClient = tencentcloud.sms.v20210111.Client;

    // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
    // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
    // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
    const clientConfig = {
        credential: {
            // secretId: "AKIDkMmxud8SZemkT3e3Nl6E9qMskU3RcfWB",
            // secretKey: "a8Xt773ztcLvSp6Ng1DD1b0DHC6wa5Nb",
        },
        region: "ap-beijing",
        profile: {
            httpProfile: {
                endpoint: "sms.tencentcloudapi.com",
            },
        },
    };

    // 实例化要请求产品的client对象,clientProfile是可选的
    const client = new SmsClient(clientConfig);
    const params = {
        PhoneNumberSet: ['+86' + info.phone],
        SmsSdkAppId: "1400822331",
        TemplateId: "1800259",
        SignName: '聪明小脑袋公众号',
        TemplateParamSet: [phoneCode, '5'],
    };
    // 先在数据库中进行查找，存在就替换code，不存在直接添加
    let num = (await userModel.find({ phone: info.phone }).lean()).length
    if (num > 0) {     
        // 数据库存在该手机号
        await userModel.updateOne({ phone: info.phone }, { code: phoneCode })
    } else {
        // 数据库不存在改手机号
        await userModel.create({ phone: info.phone, code: phoneCode, roleId: "6466ed874c2f56968e5a4103" })
    }

    client.SendSms(params).then(
        (data) => {
            res.send({
                code: 200,
                msg: '发送成功',
                CodeNum:phoneCode
            })
        },
        (err) => {
            res.send({
                code: 404,
                msg: err
            })
        }
    );

});
/* 验证码登录 */
router.post('/codeLogin', async (req, res) => {
    let data = req.body // 验证码登录
    let num = await userModel.findOne({ phone: data.phone, code: data.code }).lean()
    const token = 'Bearer ' + jwt.sign(data, 'feng', { expiresIn: 3600 * 24 * 3 })
    if (num) {
        res.send({
            code: 200,
            msg: '登录成功',
            data: num,
            token
        })
        return false
    }
    res.send({
        code: 402,
        msg: '验证码错误'
    })
})
/* 账号密码登录 */
router.post('/passLogin', async (req, res) => {
    let data = req.body
    let info = await userModel.findOne({ name: data.username }).lean()
    const token = 'Bearer ' + jwt.sign(data, 'feng', { expiresIn: 3600 * 24 * 3 })
    if (info) {
        if (info.password === data.password) {
            return res.send({
                code: 200,
                msg: '登录成功',
                data: info,
                token
            })
        }
        res.send({
            code: 404,
            msg: '密码错误'
        })
        return false
    }
    res.send({
        code: 302,
        msg: '用户名不存在'
    })
})
// 获取订单
router.get("/getorder", async (req, res) => {
    let data = await orderModel.find({}).exec()
    res.json({ msg: 'ok', data })
  })
module.exports = router;
